package gold.digger;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC731 {
    public long startExecuteTime = System.currentTimeMillis();


    /*
     * @param 此题目参考了别人代码
     * 不是因为复杂，而是因为经典
     * 未来需要再次复习此道题目
     * 官方题解简直喵喵喵
     * @return:
     */
    class MyCalendarTwo {
        TreeMap<Integer, Integer> delta;

        public MyCalendarTwo() {
            delta = new TreeMap();
        }

        public boolean book(int start, int end) {
            delta.put(start, delta.getOrDefault(start, 0) + 1);
            delta.put(end, delta.getOrDefault(end, 0) - 1);

            int active = 0;
            for (int d : delta.values()) {
                active += d;
                if (active >= 3) {
                    delta.put(start, delta.get(start) - 1);
                    delta.put(end, delta.get(end) + 1);
                    if (delta.get(start) == 0)
                        delta.remove(start);
                    return false;
                }
            }
            return true;
        }
    }


    public void run() {
        MyCalendarTwo solution = new MyCalendarTwo();
//        System.out.println(solution.book(10, 20)); // returns true
//        System.out.println(solution.book(50, 60)); // returns true
//        System.out.println(solution.book(10, 40));// returns true
//        System.out.println(solution.book(5, 15)); // returns false
//        System.out.println(solution.book(5, 10)); // returns true
//        System.out.println(solution.book(25, 55)); // returns true

        System.out.println(solution.book(10, 100)); // returns true
        System.out.println(solution.book(20, 80)); // returns true
        System.out.println(solution.book(30, 70));// returns true

    }

    public static void main(String[] args) throws Exception {
        LC731 an = new LC731();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
